package com.xunmall.message.listener;

import com.xunmall.base.dto.KafkaMessage;
import com.xunmall.message.component.message.service.MessageTemplate;
import com.xunmall.message.component.operation.service.OperationRecordService;
import com.xunmall.message.constan.enums.SendStatus;
import com.xunmall.message.dto.MessagesForm;
import com.xunmall.message.service.MessagesValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.stream.Stream;

/**
 * @Author: WangYanjing
 * @Date: 2018/12/27 10:53
 * @Description:
 */
@Component
@Slf4j
public class MessagesListener {

    @Autowired
    private MessageTemplate template;

    @Autowired
    private OperationRecordService recordService;

    @KafkaListener(topics = "${banbu.kafka.message.topic:gin-mail}")
    public void onMessage(KafkaMessage message) {
        try {
            MessagesForm messagesForm = (MessagesForm) message.getContent();
            MessagesValidate.Validate(messagesForm);
            //调用实际处理短信接口方法
            HashMap<String, Object> result = template.send(messagesForm);
            //纪录相应的纪录信息
            if ("000000".equals(result.get("statusCode"))) {
                HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
                Stream.of(data).forEach(item -> {
                    log.info(item + "=" + data.get(item));
                });
                recordService.addMsgOperation(messagesForm, SendStatus.finish, "发送完成");
            } else {
                recordService.addMsgOperation(messagesForm, SendStatus.exception, result.get("statusMsg").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
